package com.eascs.afterloan.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankRate;
import com.eascs.admin.o2o.loanAccount.entity.O2oCollectFee;
import com.eascs.admin.o2o.loanAccount.service.IO2oCollectFeesService;
import com.eascs.admin.o2o.loanAccount.serviceimpl.O2oCollectFeesService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.afterloan.dao.DeclareSignDao;
import com.eascs.afterloan.entity.DeclareSignEntity;
import com.eascs.afterloan.entity.O2oBankLoanDataTimer;
import com.eascs.afterloan.form.DeclareSignForm;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.StringUtil;

@Service
public class DeclareSignService {

	@Autowired
	DeclareSignDao declareSignDao;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Autowired
	private O2oChargeSituationService o2oChargeSituationService;

	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;

	@Reference
	IO2oCollectFeesService o2oCollectFeesService;
	
	@Autowired
	O2oCollectFeesService collectFeesService;

	public PageResult<Object[]> queryByPage(DeclareSignForm form) {
		return declareSignDao.queryByPage(form);
	}

	public int queryByCount(String userName, String cardNo) {
		return declareSignDao.queryByCount(userName, cardNo);
	}

	public String queryByLoanAppLyNo(String userName, String cardNo) {
		return declareSignDao.queryByLoanAppLyNo(userName, cardNo);
	}

	public String queryByLoanFlg(String userName, String cardNo) {
		return declareSignDao.queryByLoanFlg(userName, cardNo);
	}

	public int insert(DeclareSignEntity entity) {
		return declareSignDao.insert(entity);
	}
	
	/**
	 * O2oBankLoanDataTimer 插入放款数据
	 * @param entity
	 * @return
	 */
	public int insert(O2oBankLoanDataTimer entity) {
		return declareSignDao.insert(entity);
	}
	
	/**
	 * 根据贷款单号查询 O2oBankLoanDataTimer
	 * @param loanapplyNo
	 * @return
	 */
	public O2oBankLoanDataTimer queryByLoanapplyNo(String loanapplyNo){
		String sql = "select * from o2o_bank_loan_data_timer where loanapply_no=?";
		return declareSignDao.findEntity(sql, O2oBankLoanDataTimer.class, loanapplyNo);
	}
	
	/**
	 * O2oBankLoanDataTimer 更新放款数据
	 * @param entity
	 * @return
	 */
	public int updateById(O2oBankLoanDataTimer entity) {
		return declareSignDao.updateById(entity);
	}

	
	public DeclareSignEntity queryById(String id){
		return declareSignDao.getById(DeclareSignEntity.class, id);
	}
	
	public O2oBankLoanDataTimer queryByCollectId(String collectId){
		String sql = "select * from o2o_bank_loan_data_timer oblt where oblt.collect_fees_id=?";
		return declareSignDao.findEntity(sql, O2oBankLoanDataTimer.class, collectId);
	}
	
	public int updateById(DeclareSignEntity entity) {
		return declareSignDao.updateById(entity);
	}

	public int delete() {
		return declareSignDao.delete();
	}

	public PageResult<Object[]> queryByPageDeclareSign() {
		return declareSignDao.queryByPageDeclareSign();
	}

	public List<DeclareSignEntity> queryList() {
		return declareSignDao.queryList();
	}

	public String queryByBankName(String bankName) {
		return declareSignDao.queryByBankName(bankName);
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	public void checkJCBank(int sheetIndex, int rowIndex, Object[] rowDatas, int type) {
		String loanBankName = "";// 放款銀行
		String provinceName = "";// 省区
		String platform = ""; // 平台
		String customerName = "";// 客户姓名(借款人)
		String documentNo = "";// 客户身份证号(借款人身份证号)
		String amount = "";// 金额/万元
		String loanDate = "";// 放款日期
		String contractNum = "";// 合同编号
		String operoName = "";// 信贷经理
		String captain = "";// 团队长

		if (sheetIndex == 0 && rowIndex == 0) {
			String flag = String.valueOf(rowDatas[0] == null ? "" : rowDatas[0]);
			if (!StringUtil.isEmpty(flag) && !flag.equals("放款银行")) {
				throw new RuntimeException("模板不正确,请选择对应模板");
			}
		}

		if (sheetIndex == 0 && rowIndex >= 1) {
			for (int i = 0; i < rowDatas.length; i++) {
				if (i == 0) {
					loanBankName = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 1) {
					provinceName = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 2) {
					platform = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 3) {
					customerName = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 4) {
					documentNo = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 5) {
					amount = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 6) {
					loanDate = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 7) {
					contractNum = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 8) {
					operoName = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
				if (i == 9) {
					captain = String.valueOf(rowDatas[i] == null ? "" : rowDatas[i]);
				}
			}
			String message = "第" + rowIndex + "行：";
			if (StringUtil.isEmpty(loanBankName)) {
				throw new RuntimeException(message + "放款银行不能为空");
			}
			if (StringUtil.isEmpty(customerName)) {
				throw new RuntimeException(message + "客户姓名不能为空");
			}
			if (StringUtil.isEmpty(documentNo)) {
				throw new RuntimeException(message + "身份证号码不能为空");
			}
			if (StringUtil.isEmpty(amount)) {
				throw new RuntimeException(message + "放款金额不能为空");
			}
			if (StringUtil.isEmpty(loanDate)) {
				throw new RuntimeException(message + "放款日期不能为空");
			}
			if (!isDouble(amount)) {
				throw new RuntimeException(message + "放款金额格式不正确");
			}
			if (!isValidDate(loanDate)) {
				throw new RuntimeException(message + "放款日期格式不正确");
			}
			int queryCount = queryByCount(customerName, documentNo);

			if (queryCount == 0) {
				throw new RuntimeException(message + "未查到" + customerName + "（借款人）的贷款单");
			}
			if (queryCount > 1) {
				throw new RuntimeException(message + customerName + "有多笔贷款单在流程中，请人工核对修正后再导入。");
			}

			String loanapplyNo = queryByLoanAppLyNo(customerName, documentNo);
			if (StringUtil.isBlank(loanapplyNo)) {
				throw new RuntimeException(message + "未查到" + customerName + "（借款人）的贷款单");
			}

			String queryByLoanFlg = queryByLoanFlg(customerName, documentNo);
			if (StringUtil.isNotBlank(queryByLoanFlg)) {
				throw new RuntimeException(message + "查到" + customerName + "（借款人）的贷款单,已放款，不能导入。");
			}
			String queryByBankName = queryByBankName(loanBankName);
			if (StringUtil.isBlank(queryByBankName)) {
				throw new RuntimeException(message + "匹配不到放款银行(" + loanBankName + ")，请人工核对修正后再导入。");
			}
			if (1 == type) {
				BigDecimal amountBig = new BigDecimal(amount);
				DeclareSignEntity declareSignEntity = new DeclareSignEntity();
				declareSignEntity.setAmount(amountBig.multiply(new BigDecimal(10000)));// 将万元转为元
				declareSignEntity.setBankLoanName(queryByBankName);
				O2oLoanapplyEntity o2oloanapply = o2oLoanapplyService.findById(loanapplyNo);
				if (BankRate.BANK_GACZ.equals(queryByBankName)) {
					declareSignEntity.setFlowStatus(StatusContexts.O2O_NO);
				} else {
					declareSignEntity.setFlowStatus(StatusContexts.O2O_YES);
				}
				declareSignEntity.setIsDebit(StatusContexts.O2O_NO);
				declareSignEntity.setLoanapplyNo(loanapplyNo);
				declareSignEntity.setBillCode(o2oloanapply.getBillCode());
				declareSignEntity.setCaptain(captain);
				declareSignEntity.setContractNum(contractNum);
				declareSignEntity.setCustomerName(customerName);
				declareSignEntity.setDocumentNo(documentNo);
				try {
					declareSignEntity.setLoanDate(DateUtils.parseDate(loanDate, new String[] { "yyyy-MM-dd" }));
				} catch (ParseException e) {
					throw new RuntimeException("日期转换异常");
				}
				declareSignEntity.setOperoName(operoName);
				declareSignEntity.setPlatform(platform);
				declareSignEntity.setProvinceName(provinceName);
				insert(declareSignEntity);
			}
		}
	}
	
	/**
	 * 
	 * @param o2oloanapply
	 * @param bankName
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public void timer(O2oLoanapplyEntity o2oloanapply,String bankName){
		O2oBankLoanDataTimer bankLoanDataTimer = new O2oBankLoanDataTimer();
		bankLoanDataTimer.setLoanapplyNo(o2oloanapply.getLoanapplyNo());
		bankLoanDataTimer.setBillCode(o2oloanapply.getBillCode());
		bankLoanDataTimer.setFlowStatus(StatusContexts.O2O_YES);
		if (BankRate.BANK_GACZ.equals(bankName)) {
			O2oCollectFee collectFee = collectFeesService.queryByBillCode(o2oloanapply.getBillCode());
			if (null != collectFee) {
				bankLoanDataTimer.setCollectFeesId(collectFee.getId());
			} else {
				O2oLoanUserEntity loanUserEntity = o2oLoanapplyService.findLoanUserEntity(o2oloanapply.getLoanapplyNo(), o2oloanapply.getLoanId());
				collectFee = new O2oCollectFee();
				LoanapplyExpand loanapplyExpand = o2oChargeSituationService.queryExpandByLoanapplyNo(o2oloanapply.getLoanapplyNo());
				// 收费金额等于保证金加管理费加风险补偿金
				collectFee.setCollectMoney((loanapplyExpand.getRecDeposite().add(loanapplyExpand.getRecManger()).add(loanapplyExpand.getRecRisk())));
				collectFee.setBreakDate(new Date());
				collectFee.setCreateDate(new Date());
				collectFee.setCreateId("1");
				collectFee.setCreateName("系统管理员");
				collectFee.setStatus(StatusContexts.O2O_NEW);
				collectFee.setIsDel(StatusContexts.O2O_NO);
				collectFee.setBillCode(o2oZxServiceImpl.buildCode("DK"));
				collectFee.setLtdName(o2oloanapply.getLtdName());
				collectFee.setLtdCode(o2oloanapply.getLtdCode());
				collectFee.setLtd(o2oloanapply.getLtd());
				collectFee.setDocumentNo(loanUserEntity.getDocumentNo());
				collectFee.setLoanName(loanUserEntity.getUserFullName());
				collectFee.setLoanId(loanUserEntity.getLoanId());
				collectFee.setCollectPs(o2oloanapply.getBillCode() + "村镇放款自动打款");
				int count = collectFeesService.save(collectFee);
				if (count > 0) {
					bankLoanDataTimer.setCollectFeesId(collectFee.getId());
				}
			}
			bankLoanDataTimer.setFlowStatus(StatusContexts.O2O_NO);
		}
		bankLoanDataTimer.setIsDebit(StatusContexts.O2O_NO);
		O2oBankLoanDataTimer dataTimer = queryByLoanapplyNo(o2oloanapply.getLoanapplyNo());
		if (null == dataTimer) {
			insert(bankLoanDataTimer);
		}
	}

	/**
	 * 校验是否是double类型
	 * 
	 * @param str
	 * @return
	 */
	private boolean isDouble(String str) {
		boolean flag = true;
		try {
			Double.parseDouble(str);
		} catch (Exception e) {
			flag = false;
		}
		return flag;

	}

	/**
	 * 校验是否为正确日期格式
	 * 
	 * @param str
	 * @return
	 */
	private boolean isValidDate(String str) {
		// String str = "2007-01-02";
		if (!StringUtil.isEmpty(str)) {
			str = str.replace("/", "-");
		}
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = (Date) formatter.parse(str);
			return str.equals(formatter.format(date));
		} catch (Exception e) {
			return false;
		}
	}
	
}
